'''
给你一个 m 行 n 列的矩阵 matrix ，请按照 顺时针螺旋顺序 ，返回矩阵中的所有元素。
'''

class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        m = len(matrix)
        n = len(matrix[0])
        upper = 0
        lower = len(matrix)-1
        left = 0
        right = len(matrix[0])-1
        res = []
        while len(res) < m*n:
            if upper <= lower:
                for j in range(left,right+1):
                    res.append(matrix[upper][j])
                upper += 1
            if left <= right:
                for i in range(upper,lower + 1):
                    res.append(matrix[i][right])
                right -= 1
            if upper <= lower:
                for j in range(right,left-1,-1):
                        res.append(matrix[lower][j])
                lower -= 1
            if left <= right:
                for i in range(lower,upper-1,-1):
                    res.append(matrix[i][left])
                left += 1
        return res